package cn.jhc.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.jhc.bean.Clazz;
import cn.jhc.dao.ClassDao;
import cn.jhc.util.HibernateUtil;

public class ClassDaoImpl implements ClassDao {
	private final static Logger LOG = Logger.getLogger(ClassDaoImpl.class.getName());
	@Override
	public void save(Object o) {
		if (o instanceof Clazz) {
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(o);
			session.getTransaction().commit();
			return;
		}
		LOG.info("保存失败，请输入" + Clazz.class.getName() + "对象");
	}

	@Override
	public void update(Object o) {
		if(o instanceof Clazz){
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.update(o);
			session.getTransaction().commit();
		}
		LOG.info("更新失败，请输入" + Clazz.class.getName() + "对象");
	}

	@Override
	public void delete(Object o) {
		if(o instanceof Clazz){
			Session session = HibernateUtil.getSession();
			session.beginTransaction();
			session.delete(o);
			session.getTransaction().commit();
		}
		LOG.info("删除失败，请输入" + Clazz.class.getName() + "对象");
	}


	@Override
	public Object get(int id) {
		Clazz clazz = null;
		
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		clazz = session.get(Clazz.class, id);
		session.getTransaction().commit();
		return clazz;
	}

	@Override
	public List list() {
		String hql = "from Clazz";
		List<Clazz> clazzs = null;
		Session session =HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		clazzs = query.list();
		session.getTransaction();
		return clazzs;
	}

	@Override
	public List list(int start, int count) {
		String hql = "from Clazz";
		List<Clazz> clazzs = null;
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(start + count);
		clazzs = query.list();
		session.getTransaction().commit();
		return clazzs;
	}

	@Override
	public long getCount() {
		Long count = 0l;
		String hql = "select count(c.no) from Clazz c";
		Session session = HibernateUtil.getSession();
		session.beginTransaction();
		Query query = session.createQuery(hql);
		count = (Long)query.uniqueResult();
		session.getTransaction().commit();
		return count;
	}

}
